package wx.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wx.Code2Session;
import wx.MiniProperties;
import wx.ex.AcquireCode2SessionException;

@Slf4j
@Service
public class Code2SessionService {
    @Autowired
    MiniProperties miniProperties;

    public Code2Session getCode2Session(String code) throws AcquireCode2SessionException {
        HttpResponse response = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session?appid=" + miniProperties.getAppId() + "&secret=" + miniProperties.getAppSecret() + "&js_code=" + code + "&grant_type=authorization_code").execute();
        Code2Session code2Session = JSON.parseObject(response.body(), Code2Session.class);
        if (code2Session == null || code2Session.getOpenid() == null) {
            log.error("获取code2Session失败");
            throw new AcquireCode2SessionException("获取code2Session失败");
        }
        return code2Session;
    }
}
